//
//  AppDelegate.m
//  Zhiche-Carriage
//
//  Created by LeeBruce on 16/6/6.
//  Copyright © 2016年 LeeBruce. All rights reserved.
//

#import "AppDelegate.h"

#import "TRJPushHelper.h"

#import "NSString+jmCategory.h"

#import <AMapFoundationKit/AMapFoundationKit.h>  //高德地图
#import <AMapLocationKit/AMapLocationKit.h>      //高德地图
#import <MAMapKit/MAMapKit.h>                    //高德地图

#import "RootViewController.h"      ///根Vc
#import "WelcomeViewController.h"   ///欢迎Vc
#import "LoginViewController.h"     ///登录Vc

#import "ReceiveViewController.h"   ///待接单

#import "WKProgressHUD.h"           ///蒙板View

#import "Common.h"                  ///网络请求

#import "APIKey.h"

#import "UMMobClick/MobClick.h"                  //友盟

#import "SSKeychain.h"

#ifdef NSFoundationVersionNumber_iOS_9_x_Max

#import <UserNotifications/UserNotifications.h>

#endif


@interface AppDelegate ()
{
    UIImageView *viewImage ;
    NSTimer *timer;
}
@property (nonatomic, strong) NSMutableDictionary *gpsData;

@end

@implementation AppDelegate
{
    NSString *_uuidString;
    CGFloat _longitude;
    // 纬度
    CGFloat _latitude;
}
- (NSMutableDictionary *)gpsData {
    if (!_gpsData) {
        
        _gpsData = @{}.mutableCopy;
        
        [_gpsData setObject:@"" forKey:@"city"];
        [_gpsData setObject:@"" forKey:@"latitude"];
        [_gpsData setObject:@"" forKey:@"longitude"];
        [_gpsData setObject:@"" forKey:@"county"];
        [_gpsData setObject:@"" forKey:@"address"];
        [_gpsData setObject:@"" forKey:@"province"];
    }
    return _gpsData;
}

/***程序即将启动*/
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    
    ///1. 配置百度地图管理者
    if ( _mapManager == nil)
    {
        _mapManager = [[BMKMapManager alloc]init];
        BOOL ret = [_mapManager start:BaiDuMapKey generalDelegate:nil];
        if (!ret)
        {
            NSLog(@"manager start failed!");
        }
    }
    
    ///2. 配置窗口
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    self.window.backgroundColor = WhiteColor;
    self.window.rootViewController = [RootViewController defaultsTabBar];
    [self.window makeKeyAndVisible];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:NO];
    
    ///3. 开始定位
    if (!_locService)
    {
        _locService = [[BMKLocationService alloc] init];
        _locService.delegate = self;
        [_locService startUserLocationService];
    }
    
    if (!_geoCode) {
        _geoCode = [[BMKGeoCodeSearch alloc] init];
        _geoCode.delegate = self;
    }
    
    ///4. 添加全局网络监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    
    _hostReach = [Reachability reachabilityWithHostName:@"www.baidu.com"];
    
    //开始监听,会启动一个run loop
    [_hostReach startNotifier];
    

    ///5. 注册高德地图
    [AMapServices sharedServices].apiKey = (NSString *)APIKey;
    
    

    ///6. 友盟统计
    UMConfigInstance.appKey = UMKey;
    UMConfigInstance.channelId = @"App Store";
    //UMConfigInstance.eSType = E_UM_GAME; //仅适用于游戏场景，应用统计不用设置
    [MobClick startWithConfigure:UMConfigInstance];//配置以上参数后调用此方法初始化SDK！
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil) {
        [self checkUserToken];
        
    }
    ///6. 获取设备ID
    [self getDeviceUUID];
    
    ///7. 极光推送配置
    [[TRJPushHelper sharedHelper]  setupWithOptions:launchOptions
                                         uuidString:_uuidString];
  
    ///8. 打开定时器
    [self openTheTimer];

    return YES;
}


#pragma mark -
#pragma mark - 打开定时器
- (void)openTheTimer{
    //1800.0 秒调用一次
    timer = [NSTimer scheduledTimerWithTimeInterval:1800
                                             target:self
                                           selector:@selector(checkTheGPSData)
                                           userInfo:nil
                                            repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSRunLoopCommonModes];
}

#pragma mark - 校验GPS数据
- (void)checkTheGPSData{

    ///先检验GPS数据
    NSString *cityName = [NSString stringWithFormat:@"%@", self.gpsData[@"city"]];
    NSString *latitude = [NSString stringWithFormat:@"%@", self.gpsData[@"latitude"]];
    NSString *longitude = [NSString stringWithFormat:@"%@", self.gpsData[@"longitude"]];
    
    if (cityName.length !=0 &&
        latitude.length !=0 &&
        longitude.length !=0)
    {
        ///上传GPS数据
        [self uploadGPSData:self.gpsData];
    }
}

#pragma mark - 上传GPS数据
- (void)uploadGPSData:(NSMutableDictionary*)dicDate{
    
 
    NSLog(@"dicDate=====%@",dicDate);
    
    [Common afPostRequestWithUrlString:trail_Url
                                 parms:dicDate
                         finishedBlock:^(id responseObj)
    {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObj
                                                            options:NSJSONReadingMutableLeaves
                                                              error:nil];
        
        NSLog(@"%@",dic[@"message"]);
        
        NSString * userStatus = [NSString stringWithFormat:@"%@",dic[@"success"]];
        
        if ([userStatus isEqualToString:@"1"])
        {
            NSLog(@"GPS成功");
        }
        else
        {
            NSLog(@"GPS失败");
        }
    }failedBlock:^(NSString *errorMsg) {
        
    }];
}


#pragma mark -
#pragma mark - 监听到网络状态改变
- (void)reachabilityChanged:(NSNotification* )note{
    
    Reachability* curReach = [note object];
    
    NSParameterAssert([curReach isKindOfClass: [Reachability class]]);
    
    [self updateInterfaceWithReachability: curReach];
    
}

#pragma mark - 处理连接改变后的情况
- (void)updateInterfaceWithReachability:(Reachability *)curReach {
    //对连接改变做出响应的处理动作。
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if(status == NotReachable)
    {
        [WKProgressHUD popMessage:@"网络异常，请检查网络配置" inView:self.window duration:1.5 animated:YES];
    }
}

- (void)delayMethod{
    
    [viewImage removeFromSuperview];
}

#pragma mark - 检验用户令牌
- (void)checkUserToken{
    [Common requestWithUrlString:token_check contentType:application_json errorShow:NO finished:^(id responseObj) {
        
        if ([responseObj[@"success"] boolValue])
        {
            
        }
        else
        {
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject:nil forKey:@"login"];
            [userDefaults setObject:nil forKey:@"login_token"];
        }
        
    } failed:^(NSString *errorMsg) {
        
    }];
}


#pragma mark - 获取UUID
- (void)getDeviceUUID{
  
    CFUUIDRef uuid = CFUUIDCreate(NULL);
    
    assert(uuid != NULL);
    
    CFStringRef uuidStr = CFUUIDCreateString(NULL, uuid);
    
    if (![SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user"]) {
    
        //查看本地是否存储指定 serviceName 和 account 的密码
        [SSKeychain setPassword: [NSString stringWithFormat:@"%@", uuidStr]
                     forService:@"com.sandwish.eduOnline"
                        account:@"user"];
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline" account:@"user" ];
        //NSLog(@"SSKeychain存储显示 :第一次安装过:%@", retrieveuuid);
        
        _uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }else{
        
        //曾经安装过 则直接能打印出密码信息(即使删除了程序 再次安装也会打印密码信息) 区别于 NSUSerDefault
        
        //从钥匙串读取UUID：
        NSString *retrieveuuid = [SSKeychain passwordForService:@"com.sandwish.eduOnline"account:@"user"];
        NSLog(@"SSKeychain存储显示 :已安装过:%@", retrieveuuid);
        
        _uuidString = [NSString stringWithFormat:@"%@",retrieveuuid];
        
    }
}




#pragma mark - ************* BaiDuMapKit *************
#pragma mark - 跟踪定位代理方法，每次位置发生变化即会执行（只要定位到相应位置）
- (void)didUpdateBMKUserLocation:(BMKUserLocation *)userLocation{

    _longitude = userLocation.location.coordinate.longitude;
    
    _latitude = userLocation.location.coordinate.latitude;
    
    NSString *latitude = [NSString stringWithFormat:@"%f", _latitude];
    
    NSString *longitude = [NSString stringWithFormat:@"%f", _longitude];
    
    [self.gpsData setObject:latitude forKey:@"latitude"];
    
    [self.gpsData setObject:longitude forKey:@"longitude"];
    
    ///反地理编码
    [self reverseGeocoding];
}


#pragma mark - 反地理编码
- (void)reverseGeocoding{
    
    BMKReverseGeoCodeOption *option = [[BMKReverseGeoCodeOption alloc] init];
 
    option.reverseGeoPoint = CLLocationCoordinate2DMake(_latitude, _longitude);
  
    [_geoCode reverseGeoCode:option];
    
    BOOL flag = [_geoCode reverseGeoCode:option];
    
    if(!flag)
    {
        //NSLog(@"反geo检索发送失败");
    }
}


#pragma mark -  反地理编码成功结果返回
- (void)onGetReverseGeoCodeResult:(BMKGeoCodeSearch *)searcher
                           result:(BMKReverseGeoCodeResult *)result
                        errorCode:(BMKSearchErrorCode)error {
    if (error == BMK_SEARCH_NO_ERROR)
    {
        NSString *province = [NSString stringWithFormat:@"%@", result.addressDetail.province];
        NSString *city = [NSString stringWithFormat:@"%@", result.addressDetail.city];
        
        //区县名称
        NSString *district = [NSString stringWithFormat:@"%@", result.addressDetail.district];
        NSString *address = [NSString stringWithFormat:@"%@", result.address];
        
        [self.gpsData setObject:province forKey:@"province"];
        [self.gpsData setObject:city forKey:@"city"];
   
        [self.gpsData setObject:district forKey:@"county"];
        [self.gpsData setObject:address forKey:@"address"];

    }
    else
    {
        //NSLog(@"反地理编码失败: %u", error);
    }
}
  



#pragma mark -
#pragma mark - ************* 应用程序的生命周期 *************
/***程序暂行*/
- (void)applicationWillResignActive:(UIApplication *)application {}

/***程序进入后台*/
- (void)applicationDidEnterBackground:(UIApplication *)application {
    
    //控制定时器不被kill
    UIApplication * app = [UIApplication sharedApplication];
    __block UIBackgroundTaskIdentifier bgTask;
    bgTask = [app beginBackgroundTaskWithExpirationHandler:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid;
            }
        });
    }];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (bgTask != UIBackgroundTaskInvalid) {
                bgTask = UIBackgroundTaskInvalid ;
            }
        });
    });
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a=[dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
    
    [[NSNotificationCenter defaultCenter] postNotificationName:AppIntoBackground object:nil userInfo:dic];
    viewImage = [[UIImageView alloc]initWithFrame:CGRectMake(0, 0, Main_Width, Main_height)];
    viewImage.image = [UIImage imageNamed:@"startpage"];
    [self.window addSubview:viewImage];
    //极光推送
    [[UIApplication sharedApplication] setApplicationIconBadgeNumber:0];
    //开始持续定位
    //    self.locationManager.distanceFilter = 100.0;
    //    [self.locationManager startUpdatingLocation];
    
    //    self.locationManager.reGeocodeTimeout = 60;
    
    
}

/***程序进入前台*/
- (void)applicationWillEnterForeground:(UIApplication *)application {
    
    
    NSDate* dat = [NSDate dateWithTimeIntervalSinceNow:0];
    NSTimeInterval a = [dat timeIntervalSince1970] * 1000;
    NSString *timeString = [NSString stringWithFormat:@"%.0f", a];
    NSDictionary *dic = @{@"time":timeString};
    
    [[NSNotificationCenter defaultCenter] postNotificationName:AppIntoForeground object:nil userInfo:dic];
    [self performSelector:@selector(delayMethod) withObject:nil afterDelay:1];
    
    [self.gpsData setObject:@"" forKey:@"city"];
    [self.gpsData setObject:@"" forKey:@"latitude"];
    [self.gpsData setObject:@"" forKey:@"longitude"];
    [self.gpsData setObject:@"" forKey:@"county"];
    [self.gpsData setObject:@"" forKey:@"address"];
    [self.gpsData setObject:@"" forKey:@"province"];
    
    
    
    //极光
    [application setApplicationIconBadgeNumber:0];
    [application cancelAllLocalNotifications];
    
    
}

/***程序重新激活*/
- (void)applicationDidBecomeActive:(UIApplication *)application {
    
    
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
   
    NSString *string = [userDefaults objectForKey:@"login_token"];
    
    if (string != nil)
    {
        ///检验用户令牌
        [self checkUserToken];
    }
}

/***程序意外暂行*/
- (void)applicationWillTerminate:(UIApplication *)application {}




#pragma mark -
#pragma mark -  ************* JUPush *************
#pragma mark -

#pragma mark - 即将根据DeviceToken注册远程通知
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    [TRJPushHelper registerDeviceToken:deviceToken];
}


#pragma mark - 即将接收到的通知 (iOS10 弃用)
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo {
    [TRJPushHelper handleRemoteNotification:userInfo completion:nil];
    NSLog(@"收到通知:%@", [NSString logDic:userInfo]);
    
    if (application.applicationState != UIApplicationStateActive)
    {
        [self presentViewControllerWithUserInfo:userInfo];
    }
}


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_7_0
- (void)application:(UIApplication *)application
didReceiveRemoteNotification:(NSDictionary *)userInfo
fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    ///ios7.0以后才有此功能
    [TRJPushHelper handleRemoteNotification:userInfo completion:completionHandler];
    
    NSLog(@"userInfo-->%@\n", userInfo);
    // 应用正处理前台状态下，不会收到推送消息，因此在此处需要额外处理一下
    if (application.applicationState == UIApplicationStateActive)
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"收到推送消息"
                                                        message:userInfo[@"aps"][@"alert"]
                                                       delegate:nil
                                              cancelButtonTitle:@"取消"
                                              otherButtonTitles:@"确定", nil];
        [alert show];
    }
    return;
}

#endif
- (void)application:(UIApplication *)application
didReceiveLocalNotification:(UILocalNotification *)notification {
    [TRJPushHelper showLocalNotificationAtFront:notification];
    return;
}


#pragma mark - 通知异常
- (void)application:(UIApplication *)application
didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}


#pragma mark - 根据通知推出Vc
- (void)presentViewControllerWithUserInfo:(NSDictionary *)userInfo{
    
    ReceiveViewController *messageCtl = [[ReceiveViewController alloc] init];
    
    [self.window.rootViewController presentViewController:messageCtl
                                                 animated:YES
                                               completion:nil];
}


#pragma mark - 应用在前台收到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
       willPresentNotification:(UNNotification *)notification
         withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    NSLog(@"========%@", notification);
}


#pragma mark - 点击通知进入应用
- (void)userNotificationCenter:(UNUserNotificationCenter *)center
didReceiveNotificationResponse:(UNNotificationResponse *)response
         withCompletionHandler:(void (^)())completionHandler {
    NSLog(@"response:%@", response);
}


@end
